<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="login-ruleForm">
    <el-form-item label="账号:" prop="username">
      <el-input v-model="ruleForm.account"></el-input>
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="ruleForm.password" type="password"></el-input>
    </el-form-item>
    <el-form-item label="角色:">
      <el-select v-model="ruleForm.userType" placeholder="选择角色">
        <el-option label="学生" value="student"></el-option>
        <el-option label="教师" value="teacher"></el-option>
        <el-option label="管理员" value="manage"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: "my_login",
  data() {
    return {
      ruleForm: {
        account: '123',
        password: '123',
        userType: 'student'
      },
      rules: {
        account: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 25 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入活动名称', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 25 个字符', trigger: 'blur'}
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //向后端请求登录页面
          if (this.ruleForm.userType == "student" || this.ruleForm.userType == "manage") {
            this.$axios.post("/tb-student/login", this.ruleForm).then(res => {
              if (res.data.code == 200) {
                this.$store.commit("SET_TOKEN", res.data.data.token);
                this.$store.commit("SET_USERINFO", res.data.data.user);
                this.$router.replace("/my_index");
              } else {
                this.$router.replace("/my_login");
              }
            })
          } else if (this.ruleForm.userType == "teacher") {
            this.$axios.post("/tb-teacher/login", this.ruleForm).then(res => {
              if (res.data.code == 200) {
                this.$store.commit("SET_TOKEN", res.data.data.token);
                this.$store.commit("SET_USERINFO", res.data.data.user);
                this.$router.replace("/my_index");
              } else {
                this.$router.replace("/my_login");
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.login-ruleForm {
  margin: 300px auto;
  width: 400px;
  text-align: center;
}
</style>